package club.kynb.mall.application.flow.user;

import club.kynb.mall.application.context.AuthenticationContext;
import club.kynb.mall.application.repository.AuthRepository;
import club.kynb.mall.application.constant.AuthConst;
import club.kynb.mall.application.constant.MallResultCode;
import club.kynb.mall.application.model.model.command.AuthenticationCommand;
import club.kynb.mall.application.model.model.command.SmsAuthenticationCommand;
import club.kynb.mall.application.model.model.event.AuthFailedEvent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.common.web.exception.Errors;
import org.pizza.event.publish.EventBus;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.pizza.util.Checker;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author kynb_club@163.com
 * @since 2020/12/18 1:48 下午
 * 检查短信验证码否存正确过滤器
 */
@Slf4j
@AllArgsConstructor
@Component
public class CheckSmsVerificationCodeFilter implements Filter<AuthenticationContext> {
    private final AuthRepository authRepository;
    private final EventBus eventBus;

    @Override
    public void doFilter(AuthenticationContext authenticationContext, FilterInvoker<AuthenticationContext> filterInvoker) {
        log.info("检查短信验证码否存正确过滤器 start");
        AuthenticationCommand command = authenticationContext.getAuthenticationCommand();
        Checker.ifNotThrow(command instanceof SmsAuthenticationCommand
                , (b) -> log.error("流程配置有误，当前过滤器无法处理：{}", command.getClass().getSimpleName())
                , () -> Errors.BIZ.exception("流程配置有误，请联系开发者~"));
        SmsAuthenticationCommand smsAuthenticationCommand = (SmsAuthenticationCommand) command;
        String smsVerificationCode = smsAuthenticationCommand.getSmsVerificationCode();
        //查询短信验证码
        Optional<String> verificationCode = authRepository.getVerificationCode(getKey(command.getPhone()));
        String code = verificationCode.orElseThrow(() -> Errors.BIZ.exception(MallResultCode.CODE_11004));
        //验证短信验证码
        Checker.ifNotThrow(code.equals(smsVerificationCode), (c) -> {
            //发布验证失败事件
            eventBus.publishEvent(AuthFailedEvent.builder()
                    .phone(command.getPhone())
                    .clientType(command.getClientType())
                    .errorCode(MallResultCode.CODE_11005.code())
                    .build());
        }, () -> Errors.BIZ.exception(MallResultCode.CODE_11005));
        //清除短验
        authRepository.clear(getKey(command.getPhone()));
        log.info("检查短信验证码否存正确过滤器 end");
        filterInvoker.invoke(authenticationContext);
    }

    private String getKey(String phone) {
        return String.format("%s:%s", AuthConst.SMS_CODE, phone);
    }
}
